package com.jp.study.model.page.utils;


import java.util.ArrayList;
import java.util.List;

import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.domain.Sort.Order;

import com.jp.study.model.page.Ordering;
import com.jp.study.model.page.Paging;

/**
 * 
* @author dinghao
* @ClassName: PagingUtils 
* @Description: 操作配置分页查询参数paging对象的工具类
* @date 2018年3月21日 下午2:47:42 
*
 */
public class PagingUtils {
    private PagingUtils() {};

    /**
     * 将paging对象转换为jpa查询参数pageable
     * 
     * @param paging
     * @return
     */
    public static Pageable getPageable(Paging paging) {
        PageRequest pageRequest;

        List<Ordering> Orderings = paging.getSort();
        List<Order> orders = new ArrayList<Order>();
        if (null != Orderings && !Orderings.isEmpty()) {
            for (Ordering Ordering : Orderings) {
                Order order = parseToOrder(Ordering);
                orders.add(order);
            }
            Sort sort = new Sort(orders);
            pageRequest = new PageRequest(paging.getPageIndex(), paging.getPageSize(), sort);
        } else {
            pageRequest = new PageRequest(paging.getPageIndex(), paging.getPageSize());
        }
        return pageRequest;
    }

    private static Order parseToOrder(Ordering Ordering) {
        Order order = null;
        String direction = Ordering.getDirection();

        if (null != direction) {
            if ("desc".equals(direction.toLowerCase())) {
                order = new Order(Direction.DESC, Ordering.getField());
            } else {
                order = new Order(Direction.ASC, Ordering.getField());
            }
        } else {
            order = new Order(Ordering.getField());
        }
        return order;
    }

}